import React, { useState, useEffect, useRef } from 'react';
import { Table, Spin, Tag, message, Button } from 'antd';
import {getStockListApi} from '../../api/looping'

// 股票实时数据  定期从服务器获取股票实时价格，每秒更新一次，数据变化时高亮显示。
const StockPolling = () => {
  const [isPolling, setIsPolling] = useState(false);
  const [stockData, setStockData] = useState([]);
  const [searchParams, setSearchParams] = useState({
    page: 1,
    pageSize: 10
  });
  const [total, setTotal] = useState(0);

  const timerRef = useRef(null);
  const POLLING_INTERVAL = 3000; // 1秒

  // 模拟股票数据接口
  const fetchStockData = async (searchParams) => {
    try {
      const response = await getStockListApi(searchParams)
      const newData = response.data.list.map(item => ({
        ...item,
        priceChange: item.currentPrice - item.previousPrice // 计算价格变化
      }));
      setStockData(newData);
      setTotal(response.data.total);
    } catch (error) {
      message.error('获取股票数据失败');
    }
  };

  // 启动/停止轮询
  const togglePolling = () => {
    setIsPolling(prev => {
      const nextState = !prev;
      // if (nextState) {
      //   fetchStockData(searchParams);
      //   timerRef.current = setInterval(() => fetchStockData(searchParams), POLLING_INTERVAL);
      // } else {
      //   clearInterval(timerRef.current);
      // }
      return nextState;
    });
  };

  const onPaginationChange = (page, pageSize) => {
    clearInterval(timerRef.current);
    setSearchParams({ page, pageSize });
  };

  // 组件卸载清理
  useEffect(() => {
    fetchStockData(searchParams);
    if (isPolling) {
      timerRef.current = setInterval(() => fetchStockData(searchParams), POLLING_INTERVAL);
    } 
    return () => clearInterval(timerRef.current);
  }, [searchParams, isPolling]);

  // 数据列配置
  const columns = [
    { title: '股票代码', dataIndex: 'symbol', key: 'symbol' },
    {
      title: '当前价格',
      dataIndex: 'currentPrice',
      key: 'currentPrice',
      render: (price, item) => (
        <Tag color={item.priceChange > 0 ? 'green' : 'red'}>
          {price.toFixed(2)}
        </Tag>
      )
    },
    { title: '涨跌幅', dataIndex: 'priceChange', key: 'priceChange' },
  ];

  return (
    <div style={{ padding: 20 }}>
      <h2>实时股票行情</h2>
      <Button type="primary" onClick={togglePolling}>
        {isPolling ? '停止更新' : '启动实时更新'}
      </Button>
      {isPolling && <Spin style={{ marginLeft: 16 }} />}
      
      <Table 
        dataSource={stockData} 
        columns={columns} 
        rowKey="symbol" 
        size="small"
        style={{ marginTop: 24 }}
        pagination={{
          total: total,
          pageSize: searchParams.pageSize,
          current: searchParams.page,
          onChange: onPaginationChange
        }}
      />
    </div>
  );
};

export default StockPolling;